//MainMenu.java
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Glow;
import javafx.scene.image.Image;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MainMenu extends VBox {
    private Button newGameButton;
    private Button continueButton;
    private Button exitButton;
    private Button settingsButton;
    private VBox scoreboardBox;


    public MainMenu() {
        // 设置布局自适应
        minWidthProperty().bind(new SimpleDoubleProperty(GameConstants.getScreenWidth()));
        minHeightProperty().bind(new SimpleDoubleProperty(GameConstants.getScreenHeight()));
        prefWidthProperty().bind(minWidthProperty());
        prefHeightProperty().bind(minHeightProperty());
        maxWidthProperty().bind(minWidthProperty());
        maxHeightProperty().bind(minHeightProperty());

        // 设置菜单样式
        setAlignment(Pos.CENTER);
        setSpacing(40);
        setPadding(new Insets(20));

        // 加载自定义背景图片
        Image backgroundImage = new Image(getClass().getResourceAsStream("/images/Mainmenu.png"));
        BackgroundImage bgImg = new BackgroundImage(
                backgroundImage,
                BackgroundRepeat.NO_REPEAT,  // 改为不重复
                BackgroundRepeat.NO_REPEAT,  // 改为不重复
                BackgroundPosition.CENTER,
                new BackgroundSize(
                        GameConstants.getScreenWidth(),  // 使用当前屏幕宽度
                        GameConstants.getScreenHeight(), // 使用当前屏幕高度
                        false, false,  // 不保持宽高比
                        true, true    // 覆盖整个区域
                )
        );
        setBackground(new Background(bgImg));

        // 初始化按钮
        newGameButton = new Button("新的冒险");
        continueButton = new Button("继续冒险");
        settingsButton = new Button("游戏设置");
        exitButton = new Button("退出游戏");

        // 设置按钮样式
        styleButton(newGameButton, Color.rgb(46, 204, 113));
        styleButton(continueButton, Color.rgb(52, 152, 219));
        styleButton(settingsButton, Color.rgb(155, 89, 182));
        styleButton(exitButton, Color.rgb(231, 76, 60));

        continueButton.setDisable(!PlayerDataManager.hasSavedPlayer());

        // 创建排行榜面板
        createScoreboard();

        // 创建顶部栏（玩家名字）
        HBox topBar = createTopBar();

        // 创建主内容容器
        VBox content = createContent();

        // 使用BorderPane作为根布局
        BorderPane rootPane = new BorderPane();
        rootPane.setBackground(Background.EMPTY);

        // 创建一个顶部容器，包含排行榜和玩家信息
        HBox topContainer = new HBox();
        topContainer.setAlignment(Pos.TOP_LEFT);
        topContainer.setPadding(new Insets(20));
        topContainer.setSpacing(20);

        // 将排行榜放在顶部左侧
        topContainer.getChildren().add(scoreboardBox);

        // 创建一个占位区域，让玩家信息可以推到右侧
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);

        // 将玩家信息放在顶部右侧
        HBox playerBox = new HBox(createTopBar());
        playerBox.setAlignment(Pos.TOP_RIGHT);

        topContainer.getChildren().addAll(spacer, playerBox);

        // 将顶部容器放在BorderPane的顶部
        rootPane.setTop(topContainer);

        // 将主内容放在中央
        rootPane.setCenter(createContent());

        // 添加组件
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(rootPane);

        getChildren().add(stackPane);
    }

    private void createScoreboard() {
        scoreboardBox = new VBox(2);
        scoreboardBox.setAlignment(Pos.TOP_LEFT);
        scoreboardBox.setPadding(new Insets(5, 10, 5, 10));

        // 根据分辨率设置大小
        double prefWidth = GameConstants.getScreenWidth() * 0.2; // 占屏幕宽度的20%
        double prefHeight = GameConstants.getScreenHeight() * 0.16; // 占屏幕高度的16%
        scoreboardBox.setPrefSize(prefWidth, prefHeight);
        scoreboardBox.setMaxSize(prefWidth, prefHeight);

        // 边框样式
        scoreboardBox.setBorder(new Border(new BorderStroke(
                Color.WHITESMOKE,
                BorderStrokeStyle.SOLID,
                new CornerRadii(3),
                new BorderWidths(1)
        )));

        updateScoreboard();
    }

    private HBox createTopBar() {
        String playerName = PlayerDataManager.loadPlayerName();
        Label playerLabel = new Label(playerName != null ? "玩家: " + playerName : "");

        // 根据分辨率设置字体大小
        double fontSize = GameConstants.getScreenHeight() * 0.05;
        playerLabel.setFont(Font.font("Arial", FontWeight.BOLD, fontSize));
        playerLabel.setTextFill(Color.WHITE);
        playerLabel.setEffect(new DropShadow(3, Color.BLACK));

        // 限制最大宽度并允许换行
        playerLabel.setMaxWidth(GameConstants.getScreenWidth() * 0.3);
        playerLabel.setWrapText(true);

        HBox topBar = new HBox(playerLabel);
        topBar.setAlignment(Pos.TOP_RIGHT);
        topBar.setPadding(new Insets(10));
        topBar.setMaxWidth(Double.MAX_VALUE);
        HBox.setHgrow(topBar, Priority.ALWAYS);

        return topBar;
    }


    private VBox createContent() {
        // 按钮容器
        VBox buttons = new VBox(20, newGameButton, continueButton, settingsButton, exitButton); // 减少按钮间距
        buttons.setAlignment(Pos.CENTER);
        buttons.setPadding(new Insets(10));

        // 主内容容器
        VBox content = new VBox(25, buttons); // 减少标题和按钮间距
        content.setAlignment(Pos.CENTER);
        content.setPadding(new Insets(30)); // 减少内边距

        return content;
    }

    // 更新排行榜内容
    public void updateScoreboard() {
        scoreboardBox.getChildren().clear();

        List<PlayerDataManager.ScoreEntry> scores = PlayerDataManager.loadScores();

        // 标题
        Label title = new Label("排行榜");
        title.setFont(Font.font("Arial", FontWeight.BOLD, 16));
        title.setTextFill(Color.WHITE);
        scoreboardBox.getChildren().add(title);

        // 确保不显示重复记录
        Set<String> displayedEntries = new HashSet<>();
        int count = 0;

        for (PlayerDataManager.ScoreEntry entry : scores) {
            String entryKey = entry.name + "-" + entry.score;
            if (!displayedEntries.contains(entryKey) && count < 3) {
                Label entryLabel = new Label(String.format("%s —— %d",
                        entry.name, entry.score));
                entryLabel.setFont(Font.font("Arial", 14));
                entryLabel.setTextFill(Color.WHITE);
                scoreboardBox.getChildren().add(entryLabel);

                displayedEntries.add(entryKey);
                count++;
            }
        }

        // 如果没有记录，显示提示
        if (scoreboardBox.getChildren().size() == 1) {
            Label emptyLabel = new Label("暂无记录");
            emptyLabel.setFont(Font.font("Arial", FontPosture.ITALIC, 12));
            emptyLabel.setTextFill(Color.LIGHTGRAY);
            scoreboardBox.getChildren().add(emptyLabel);
        }
    }

    public static void styleButton(Button button, Color baseColor) {
        // 创建渐变效果
        LinearGradient gradient = new LinearGradient(
                0, 0, 0, 1, true, CycleMethod.NO_CYCLE,
                new Stop(0, baseColor.deriveColor(0, 1, 1.2, 1)),
                new Stop(0.5, baseColor),
                new Stop(1, baseColor.deriveColor(0, 1, 0.8, 1))
        );

        // 设置按钮样式
        button.setFont(Font.font("Arial", FontWeight.BOLD, 28));
        button.setTextFill(Color.WHITE);
        button.setBackground(new Background(new BackgroundFill(
                gradient,
                new CornerRadii(10),
                Insets.EMPTY
        )));
        button.setBorder(new Border(new BorderStroke(
                baseColor.deriveColor(0, 1, 0.7, 1),
                BorderStrokeStyle.SOLID,
                new CornerRadii(10),
                new BorderWidths(3)
        )));

        // 添加阴影效果
        DropShadow shadow = new DropShadow(10, baseColor.deriveColor(0, 1, 0.5, 0.7));
        button.setEffect(shadow);

        // 悬停效果
        Glow hoverGlow = new Glow(0.7);
        button.setOnMouseEntered(e -> {
            button.setEffect(new DropShadow(15, baseColor.deriveColor(0, 1, 0.5, 0.9)));
            button.setScaleX(1.05);
            button.setScaleY(1.05);
        });
        button.setOnMouseExited(e -> {
            button.setEffect(shadow);
            button.setScaleX(1.0);
            button.setScaleY(1.0);
        });

        // 按下效果
        button.setOnMousePressed(e -> {
            button.setScaleX(0.98);
            button.setScaleY(0.98);
        });
        button.setOnMouseReleased(e -> {
            button.setScaleX(1.05);
            button.setScaleY(1.05);
        });
    }

    public void setNewGameButtonAction(javafx.event.EventHandler<javafx.event.ActionEvent> handler) {
        newGameButton.setOnAction(handler);
    }

    public void setContinueButtonAction(javafx.event.EventHandler<javafx.event.ActionEvent> handler) {
        continueButton.setOnAction(handler);
    }

    public void setSettingsButtonAction(javafx.event.EventHandler<javafx.event.ActionEvent> handler) {
        settingsButton.setOnAction(handler);
    }

    public void setExitButtonAction(javafx.event.EventHandler<javafx.event.ActionEvent> handler) {
        exitButton.setOnAction(handler);
    }
}
